package com.genius.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.hutool.json.JSONUtil;
import com.genius.constant.LoginStatusConstants;
import com.genius.core.JSONResult;
import com.genius.core.LoginUser;
import com.genius.enums.ResponseType;
import com.genius.exception.GraceException;
import com.genius.feign.LogServiceFeign;
import com.genius.feign.UserServiceFeign;
import com.genius.monitor.pojo.LoginLog;
import com.genius.utils.IpUtils;
import com.genius.utils.SecurityUtils;
import com.genius.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;

import static com.genius.constant.SecurityConstants.INNER;

@Slf4j
@Service
public class LoginUserService {

    @Autowired
    private LogServiceFeign logServiceFeign;

    @Autowired
    private UserServiceFeign userServiceFeign;

    public LoginUser login(String username, String password){
        JSONResult jsonResult = userServiceFeign.selectUserByUserName(username,INNER);
        Object object = jsonResult.getData();
        if(object == null){
            saveLoginLog(username, LoginStatusConstants.LOGIN_FAIL, ResponseType.USER_NOT_EXIST_ERROR.msg());
            GraceException.display(ResponseType.USER_NOT_EXIST_ERROR);
        }
        LoginUser loginUser = JSONUtil.parse(object).toBean(LoginUser.class);
        boolean matches = SecurityUtils.matchesPassword(password,loginUser.getUser().getPassword());
        if(!matches){
            saveLoginLog(username, LoginStatusConstants.LOGIN_FAIL,ResponseType.USER_PARAMS_ERROR.msg());
            GraceException.display(ResponseType.USER_PARAMS_ERROR);
        }else {
            setUserAgent(loginUser);
            saveLoginLog(username, LoginStatusConstants.LOGIN_SUCCESS,"登录成功");
        }
        return loginUser;
    }

    private void saveLoginLog(String username, String status, String message) {
        LoginLog loginLog = new LoginLog();
        Long loginId = IdUtil.getSnowflake().nextId();
        loginLog.setLoginId(loginId);
        loginLog.setUsername(username);
        loginLog.setStatus(status);
        loginLog.setMsg(message);
        setUserAgent(loginLog);
        logServiceFeign.insertLoginLog(loginLog, INNER);
    }

    private void setUserAgent(LoginLog loginLog){
        String userAgentStr = ServletUtils.getRequest().getHeader(HttpHeaders.USER_AGENT);
        UserAgent userAgent = UserAgentUtil.parse(userAgentStr);
        // 获取客户端IP
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginLog.setIpaddr(ip);
        // 获取登陆属地
        String loginLocation = IpUtils.getRealAddressByIP(ip);
        loginLog.setLoginLocation(loginLocation);
        // 获取客户端操作系统
        String os = userAgent.getPlatform().toString()+" "+userAgent.getOsVersion();
        loginLog.setOs(os);
        // 获取客户端浏览器
        String browser = userAgent.getBrowser().getName();
        loginLog.setBrowser(browser);
    }

    /**
     * 设置用户代理信息
     * @param loginUser 登录信息
     */
    private void setUserAgent(LoginUser loginUser) {
        String userAgentStr = ServletUtils.getRequest().getHeader(HttpHeaders.USER_AGENT);
        log.info("User-Agent：{}.", userAgentStr);
        UserAgent userAgent = UserAgentUtil.parse(userAgentStr);
        loginUser.setBrowser(userAgent.getBrowser().toString());
        loginUser.setVersion(userAgent.getVersion());
        loginUser.setOs(userAgent.getPlatform().toString()+" "+userAgent.getOsVersion());
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        loginUser.setIpAddr(ip);
    }
}
